package org.example.util;


public class ExceptionUtil {
    private static String e2sOneNoThread(Exception e) {
        StringBuilder sb = new StringBuilder();
        sb.append(e);
        Throwable throwable = e.getCause();
        if (throwable != null) {
            String message = throwable.getMessage();
            if (message != null) {
                sb.append(" : ");
                sb.append(message);
            }
        }
        return sb.toString();
    }

    /**
     * 错误堆栈的内容
     */
    public static String show(Exception e) {
        StringBuilder sb = new StringBuilder();
        sb.append(e2sOneNoThread(e));
        sb.append("\n");
        for (StackTraceElement ste : e.getStackTrace()) {
            sb.append("at ");
            sb.append(ste);
            sb.append("\n");
        }
        sb.append("threadName:" + Thread.currentThread().getName());
        sb.append("\n");
        return sb.toString();
    }

    /**
     * 错误堆栈的内容
     *
     * @param t
     * @return
     */
    public static String show(Throwable t) {
        StringBuilder sb = new StringBuilder();
        sb.append(t);
        sb.append("\n");
        for (StackTraceElement ste : t.getStackTrace()) {
            sb.append("at ");
            sb.append(ste);
            sb.append("\n");
        }
        return sb.toString();
    }

    public static String show() {
        return show(-1);
    }

    public static String show(int len) {
        StringBuilder sb = new StringBuilder();
        StackTraceElement[] elements = Thread.currentThread().getStackTrace();
        if (len > 0) {
            len = Math.min(len, elements.length);
        } else {
            len = elements.length;
        }
        for (int i = 0; i < len; i++) {
            StackTraceElement ste = elements[i];
            sb.append("at ");
            sb.append(ste);
            sb.append("\n");
        }
        return sb.toString();
    }
}
